import sys
import time
import json
from datetime import datetime
from selenium import webdriver
from selenium.common import exceptions
from selenium.webdriver.chrome.options import Options
import urllib.parse
from mongoengine import *


class privateuser(Document):
    nickname = StringField()
    gender = IntField()
    city = StringField()
    followerCount = IntField()
    uid = StringField()
    addTime = DateTimeField()
    accountUid = StringField()
    accountName = StringField()
    updatetime = DateTimeField()
    postCount = IntField()
    fansCount = IntField()
    searched = IntField()
    privateList = ListField()
    isFans = IntField()
    isClicked = IntField()
    isDelete = IntField()
    meta = {
        'strict':False
    }


class newprivateuser(Document):
    nickname = StringField()
    gender = IntField()
    city = StringField()
    followerCount = IntField()
    uid = StringField()
    addTime = DateTimeField()
    accountUid = StringField()
    accountName = StringField()
    updatetime = DateTimeField()
    postCount = IntField()
    fansCount = IntField()
    searched = ListField()
    firstClickUser = ListField()
    allClickUser = ListField()
    isClicked = IntField()
    isDelete = IntField()
    meta = {
        'strict':False
    }

class myprivateaccounts(Document):
    name = StringField()
    uid = StringField()
    addTime = DateTimeField()
    updatetime = DateTimeField()
    isDelete = IntField()
    meta = {
        'strict':False
    }


def NewDriver():
    chrome_options = Options()
    # chrome_options.add_argument("user-data-dir=" + path2 + 'userlist' + accountName)
    chrome_options.add_argument("user-data-dir=" + path2 + 'searchprivate' + accountName)
    driver = webdriver.Chrome(path, options=chrome_options)
    driver.maximize_window()
    return driver


def getFans(driver,accountUid,accountName):
    global nowPages
    time.sleep(1)
    followList = driver.find_elements_by_class_name('follow_item')
    counts = driver.find_elements_by_class_name('info_connect')
    address = driver.find_elements_by_class_name('info_add')
    if len(followList) != 0:
        for i in range(0,len(followList)):
            print(str(i+1) + 'of'+ str(len(followList)))
            url = '?' + followList[i].get_attribute('action-data')
            query = dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(url).query))
            # print(query['uid'],query['fnick'],query['sex'])
            sex = 3
            try:
                if query['sex'] == 'm':
                    sex = 0
                elif query['sex'] == 'f':
                    sex = 1
            except:
                sexIcon = followList[i].find_element_by_class_name('W_icon')
                tempStr = sexIcon.get_attribute('class').split(" ")
                if 'icon_male' in tempStr:
                    sex = 0
                elif 'icon_female' in tempStr:
                    sex = 1
            flolow = counts[i].find_elements_by_tag_name('a')[0].get_attribute('text')
            fans = counts[i].find_elements_by_tag_name('a')[1].get_attribute('text')
            post = counts[i].find_elements_by_tag_name('a')[2].get_attribute('text')
            try:
                city = address[i].find_elements_by_tag_name('span')[0].get_attribute('textContent')
            except:
                city = address[i].get_attribute('textContent')
            if city[0:2] == '地址':
                city = city[2:]

            oneUser = newprivateuser.objects(uid = query['uid'],accountUid = accountUid)
            if len(oneUser) == 0:
                newdata = newprivateuser(
                    nickname = query['fnick'],
                    gender = sex,
                    city = city,
                    followerCount = flolow,
                    fansCount = fans,
                    postCount = post,
                    uid = query['uid'],
                    searched = [],
                    addTime = datetime.now(),
                    accountUid = accountUid,
                    accountName = accountName,
                    updatetime = datetime.now(),
                    isClicked = 0,
                    isDelete = 0
                )
                newdata.save()
                time.sleep(1)
            else:
                pass
        print(u"下一页")
        try:
            nextPage = driver.find_element_by_class_name('next')
        except:
            driver.refresh()
            getFans(driver,accountUid,accountName)
        if nextPage.get_attribute('href') == None:
            print('完成')
            driver.quit()
        # nextPage.click()
        fansUrl = "https://weibo.com/{UID}/fans?cfs=600&relate=fans&t=1&f=1&type=&Pl_Official_RelationFans__88_page={page}#Pl_Official_RelationFans__88"
        print("nextpage",nowPages,fansUrl.format(UID=accountUid, page=nowPages))
        driver.get(fansUrl.format(UID=accountUid, page=nowPages))
        nowPages = nowPages + 1
        getFans(driver,accountUid,accountName) 
    else:
        driver.quit()




if __name__ == '__main__':
    # accountName = sys.argv[1]
    # accountUid = sys.argv[2]
    index = int(sys.argv[1])
    # c = sys.argv[3] 
    # mode = int(sys.argv[4])
    # accountUid = "1935908524"
    # accountName = "怪兽-上上"
    mode = 1
    path = 'd:/work/weiboprivate/python/chromedriver.exe'
    path2 = 'd:/work/weiboprivate/profile/'
    if mode == 1:
        path = 'd:/weiboprivate/python/chromedriver.exe'
        path2 = 'd:/weiboprivate/profile/'
        connect('weibo', host='1.15.92.12', port=27817)
        # connect('weibo', host='localhost', port=27017)
    else:
        connect('weibo', host='1.15.92.12', port=27817)
        # connect('weibo', host='localhost', port=27017)
    
    accountlist = myprivateaccounts.objects(isDelete=0)
    accountName = accountlist[index]['name']
    accountUid = accountlist[index]['uid']

    nowPages = 0

    driver = NewDriver()
    fansUrl = "https://weibo.com/{UID}/fans?cfs=600&relate=fans&t=1&f=1&type=&Pl_Official_RelationFans__88_page={page}#Pl_Official_RelationFans__88"
    driver.get(fansUrl.format(UID=accountUid, page=1))
    time.sleep(2)
    getFans(driver,accountUid,accountName)
    driver.quit()